package com.floreantpos.ui.dialog;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

import com.floreantpos.main.Application;
import com.floreantpos.model.ActionHistory;
import com.floreantpos.model.MenuItem;
import com.floreantpos.model.PosTransaction;
import com.floreantpos.model.Ticket;
import com.floreantpos.model.TicketItem;
import com.floreantpos.model.dao.ActionHistoryDAO;
import com.floreantpos.model.dao.MenuItemDAO;
import com.floreantpos.model.dao.TicketDAO;
import com.floreantpos.print.PosPrintService;
import com.floreantpos.services.PosTransactionService;
import com.floreantpos.swing.GlassPane;
import com.googlecode.floreo.ecf.bematech.BematechMP2100;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class ECFDialog extends JFrame {
  
  private GlassPane glassPane;
  
  public ECFDialog() {
    super();
    initComponents();
    
    setIconImage(Application.getPosWindow().getIconImage());
    setTitle(Application.getTitle() + " - Funções do ECF");
    
    glassPane = new GlassPane();
    setGlassPane(glassPane);
  }
  
  public void setGlassPaneVisible(boolean b) {
    glassPane.setVisible(b);
  }
  
  private void initComponents() {
    titlePanel1 = new com.floreantpos.ui.TitlePanel();
    transparentPanel4 = new com.floreantpos.swing.TransparentPanel();
    transparentPanel2 = new com.floreantpos.swing.TransparentPanel();
    transparentPanel3 = new com.floreantpos.swing.TransparentPanel();
    btnLeituraX = new com.floreantpos.swing.PosButton();
    btnReducaoZ = new com.floreantpos.swing.PosButton();
    btnMemoriaFiscalPorData = new com.floreantpos.swing.PosButton();
    btnFormasDePagamento = new com.floreantpos.swing.PosButton();
    btnHorarioDeVerao = new com.floreantpos.swing.PosButton();
    btnCancelaCupomFiscal = new com.floreantpos.swing.PosButton();
    transparentPanel1 = new com.floreantpos.swing.TransparentPanel();
    btnFinish = new com.floreantpos.swing.PosButton();
    
    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    titlePanel1.setTitle("Funções do ECF");
    getContentPane().add(titlePanel1, java.awt.BorderLayout.NORTH);
    
    transparentPanel4.setLayout(new java.awt.BorderLayout());
    
    transparentPanel4.setOpaque(true);
    transparentPanel2.setLayout(new java.awt.GridBagLayout());
    
    transparentPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
    transparentPanel3.setLayout(new java.awt.GridLayout(2, 2, 5, 5));
    
    btnLeituraX.setText("Executar Leitura X");
    btnLeituraX.setPreferredSize(new java.awt.Dimension(220, 60));
    btnLeituraX.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnLeituraXActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnLeituraX);
    
    btnReducaoZ.setText("Executar Reducao Z");
    btnReducaoZ.setPreferredSize(new java.awt.Dimension(220, 60));
    btnReducaoZ.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnReducaoZActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnReducaoZ);
    
    btnCancelaCupomFiscal.setText("Cancelar Cupom Fiscal");
    btnCancelaCupomFiscal.setPreferredSize(new java.awt.Dimension(220, 60));
    btnCancelaCupomFiscal.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnCancelaCupomFiscalActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnCancelaCupomFiscal);
    
    btnMemoriaFiscalPorData.setText("Memória Fiscal por Data");
    btnMemoriaFiscalPorData.setPreferredSize(new java.awt.Dimension(220, 60));
    btnMemoriaFiscalPorData.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnMemoriaFiscalPorDataActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnMemoriaFiscalPorData);
    
    btnFormasDePagamento.setText("Configurar Formas de Pagamento");
    btnFormasDePagamento.setPreferredSize(new java.awt.Dimension(220, 60));
    btnFormasDePagamento.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnFormasDePagamentoActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnFormasDePagamento);
    
    btnHorarioDeVerao.setText("Configurar Horário de Verão");
    btnHorarioDeVerao.setPreferredSize(new java.awt.Dimension(220, 60));
    btnHorarioDeVerao.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnHorarioDeVeraoActionPerformed(evt);
      }
    });
    
    transparentPanel3.add(btnHorarioDeVerao);   
    
    transparentPanel2.add(transparentPanel3, new java.awt.GridBagConstraints());
    
    transparentPanel4.add(transparentPanel2, java.awt.BorderLayout.CENTER);
    
    transparentPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));
    
    btnFinish.setText(com.floreantpos.POSConstants.FINISH);
    btnFinish.setPreferredSize(new java.awt.Dimension(120, 60));
    btnFinish.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        btnFinishActionPerformed(evt);
      }
    });
    
    transparentPanel1.add(btnFinish);
    
    transparentPanel4.add(transparentPanel1, java.awt.BorderLayout.SOUTH);
    
    getContentPane().add(transparentPanel4, java.awt.BorderLayout.CENTER);
    
    pack();
  }
  
  private void btnFinishActionPerformed(java.awt.event.ActionEvent evt) {
    dispose();
  }
  
  private void btnLeituraXActionPerformed(java.awt.event.ActionEvent evt) {
    BematechMP2100.leituraX();
  }
  
  private void btnReducaoZActionPerformed(java.awt.event.ActionEvent evt) {
    BematechMP2100.reducaoZ();
  }
  
  private void btnMemoriaFiscalPorDataActionPerformed(java.awt.event.ActionEvent evt) {
    String dataInicial = JOptionPane.showInputDialog("Data Inicial (dd/mm/aaaa): ");
    String dataFinal = JOptionPane.showInputDialog("Data Final (dd/mm/aaaa): ");
    
    if (dataInicial.isEmpty() || dataFinal.isEmpty()) {
      JOptionPane.showMessageDialog(null, "Data Inicial e Final são obrigatórias", com.floreantpos.POSConstants.MDS_POS, JOptionPane.ERROR_MESSAGE, null);
      return;      
    }
    
    Date dataInicialAsDate, dataFinalAsDate;
    
    try {
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy", new Locale("pt", "BR"));
      simpleDateFormat.setLenient(false);
      dataInicialAsDate = simpleDateFormat.parse(dataInicial);
      dataFinalAsDate = simpleDateFormat.parse(dataFinal);
    } catch (ParseException ex) {      
      JOptionPane.showMessageDialog(null, "Data(s) Inválida(s)", com.floreantpos.POSConstants.MDS_POS, JOptionPane.ERROR_MESSAGE, null);      
      Logger.getLogger(ECFDialog.class.getName()).log(Level.WARNING, null, ex);
      return;      
    }
    
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -1);
    if (dataFinalAsDate.after(calendar.getTime())) {
      JOptionPane.showMessageDialog(null, "Data Final deve ser menor que a Data Atual", com.floreantpos.POSConstants.MDS_POS, JOptionPane.ERROR_MESSAGE, null);      
      return;
    }    
    
    if (dataInicialAsDate.after(dataFinalAsDate)) {
      JOptionPane.showMessageDialog(null, "Data Inicial deve ser menor que Data Final", com.floreantpos.POSConstants.MDS_POS, JOptionPane.ERROR_MESSAGE, null);
      return;      
    }
    
    BematechMP2100.leituraMemoriaFiscalPorData(dataInicial, dataFinal);
  }
  
  private void btnHorarioDeVeraoActionPerformed(java.awt.event.ActionEvent evt) {
    BematechMP2100.programaHorarioVerao();
  }
  
  private void btnCancelaCupomFiscalActionPerformed(java.awt.event.ActionEvent evt) {
    String numeroCupom = BematechMP2100.numeroCupom().trim();
    if (BematechMP2100.cancelaCupom()) {
      Boolean isTicketCanceled = true;
      TicketDAO ticketDAO = new TicketDAO();
      Ticket ticket = ticketDAO.findTicketByCupomFiscal(numeroCupom);
      if (ticket != null) {
        
        ticket.setCupomFiscalCancelado(true);
        ticketDAO.saveOrUpdate(ticket);
        
        if (!ticket.isVoided()) {
          
          ticket = ticketDAO.initializeTicket(ticket);
          
          String amount = "";
          if (ticket.getGratuity() != null) {
            amount = Application.getCurrencySymbol() + " " + Application.formatNumber(ticket.getTotalAmount() + ticket.getGratuity().getAmount());
          } else {
            amount = Application.getCurrencySymbol() + " " + Application.formatNumber(ticket.getTotalAmount());
          }
          
          if (ticket.getTransactionType().equals(PosTransaction.TYPE_CASH)) {
            JOptionPane.showMessageDialog(this, "Confirme a retirada de " + amount + " do caixa.");
          }          
          
          try {
            PosTransactionService service = PosTransactionService.getInstance();
            service.refundTicket(ticket);
            
            ActionHistoryDAO.getInstance().saveHistory(Application.getCurrentUser(), ActionHistory.REOPEN_CHECK, com.floreantpos.POSConstants.CHK_NO + ticket.getId());
            
            ticket.setDrawerResetted(false);            
          } catch (Exception e) {
            isTicketCanceled = false;
            JOptionPane.showMessageDialog(null, "Erro ao reabrir o Pedido. O pedido deve ser reaberto e cancelado manualmente.\nMensagem: " + e, com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
          }          
        } else {
          isTicketCanceled = false;
          JOptionPane.showMessageDialog(null, "Pedido já havia sido cancelado.", com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
        }
        
        if (!ticket.isClosed() || !ticket.getTotalAmount().equals(ticket.getDueAmount())) {
          Boolean isWasted = false;          

          if (JOptionPane.showConfirmDialog(null, "Os itens do Cupom Fiscal cancelado foram descartados?", com.floreantpos.POSConstants.MDS_POS, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            isWasted = true;
          }  
          
          try {
            ticket.setWasted(isWasted);
            ticket.setVoidedBy(Application.getCurrentUser());
            ticket.setVoidReason("Cancelamento do Cupom Fiscal");

            ticketDAO.voidTicket(ticket);

            try {
              PosPrintService.printToKitchen(ticket);
            } catch (Exception ee) {
              String message = com.floreantpos.POSConstants.ERROR_PRINTING_CANCEL_KITCHEN;
              POSMessageDialog.showError(Application.getPosWindow(), message, ee);
            }          

            ActionHistoryDAO.getInstance().saveHistory(Application.getCurrentUser(), ActionHistory.VOID_CHECK, com.floreantpos.POSConstants.CHK_NO + ":" + ticket.getId() + "; Total" + ": " + Application.formatNumber(ticket.getTotalAmount()));          
          } catch (Exception e) {
            isTicketCanceled = false;
            JOptionPane.showMessageDialog(null, "Erro ao cancelar o Pedido. O pedido deve ser cancelado manualmente.\nMensagem: " + e, com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
          }                   
        } else {
          isTicketCanceled = false;
          JOptionPane.showMessageDialog(null, "Não foi possível cancelar o pedido.", com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
        }        
        if (ticket.isWasted()) {
          List<TicketItem> ticketItems = ticket.getTicketItems();
          if (ticketItems != null) {
            MenuItemDAO menuItemDAO = new MenuItemDAO();
            for (TicketItem ticketItem : ticketItems) {
              MenuItem menuItem = menuItemDAO.get(ticketItem.getItemId());
              if (menuItem.isUpdateInventory()) {
                menuItem.setQtyOnHand(menuItem.getQtyOnHand() - ticketItem.getItemCount());
                menuItemDAO.saveOrUpdate(menuItem);
              }
            }
          }          
        }
        if (isTicketCanceled) {
          JOptionPane.showMessageDialog(null, "Cupom Fiscal e Pedido cancelados com sucesso.", com.floreantpos.POSConstants.MDS_POS, JOptionPane.INFORMATION_MESSAGE, null);
        } else {
          JOptionPane.showMessageDialog(null, "Não foi possível reabrir ou cancelar o Pedido.\nEfetue a reabertura e/ou cancelamento do Pedido manualmente.", com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
        }
      } else {
        JOptionPane.showMessageDialog(null, "Não foi possível cancelar o Pedido.", com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
      }
    } else {
      JOptionPane.showMessageDialog(null, "Não foi possível cancelar o Cupom Fiscal.", com.floreantpos.POSConstants.ERROR_MESSAGE, JOptionPane.ERROR_MESSAGE, null);
    }
  }
  
  private void btnFormasDePagamentoActionPerformed(java.awt.event.ActionEvent evt) {
    if (JOptionPane.showConfirmDialog(null, "Configurar as Formas de Pagamento?", com.floreantpos.POSConstants.MDS_POS, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
      if (!BematechMP2100.verificaFormasPagamento().contains("Debito")) {
        BematechMP2100.programaFormaPagamentoMFD("Debito", "0");
      }
      if (!BematechMP2100.verificaFormasPagamento().contains("Credito")) {
        BematechMP2100.programaFormaPagamentoMFD("Credito", "0");
      }
      if (!BematechMP2100.verificaFormasPagamento().contains("Beneficio")) {
        BematechMP2100.programaFormaPagamentoMFD("Beneficio", "0");
      }
      if (!BematechMP2100.verificaFormasPagamento().contains("Vale")) {
        BematechMP2100.programaFormaPagamentoMFD("Vale", "0");
      }
      JOptionPane.showMessageDialog(null, "Certifique-se que as Formas de Pagamento foram criadas efetuando uma Leitura X.", com.floreantpos.POSConstants.MDS_POS, JOptionPane.INFORMATION_MESSAGE, null);      
    }    
  }
  
  public void open() {
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    
    int width = 800;
    int height = 600;
    
    int x = (screenSize.width - 800) / 2;
    int y = (screenSize.height - 600) / 2;
    
    setSize(width, height);
    
    setLocation(x, y);
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setVisible(true);
  }
  
  private com.floreantpos.swing.PosButton btnFinish;
  private com.floreantpos.swing.PosButton btnLeituraX;
  private com.floreantpos.swing.PosButton btnReducaoZ;
  private com.floreantpos.swing.PosButton btnMemoriaFiscalPorData;
  private com.floreantpos.swing.PosButton btnHorarioDeVerao;
  private com.floreantpos.swing.PosButton btnFormasDePagamento;
  private com.floreantpos.swing.PosButton btnCancelaCupomFiscal;
  private com.floreantpos.ui.TitlePanel titlePanel1;
  private com.floreantpos.swing.TransparentPanel transparentPanel1;
  private com.floreantpos.swing.TransparentPanel transparentPanel2;
  private com.floreantpos.swing.TransparentPanel transparentPanel3;
  private com.floreantpos.swing.TransparentPanel transparentPanel4;
  
}
